/**
 * Company : Thai Informatic System Co., Ltd.
 * Created By : Dr.Tree
 * Created On : Feb 28, 2012  3:32:38 PM 
 * e-Mail : chatree@tis.co.th
 * Mobile Phone : (+66) 087-921-5115
 * Package Name : sap.business.mm.inbound
 * File Name : MmPurchaseOrderService.java
 * TODO
 */
package sap.business.mm.inbound;

import java.util.ArrayList;
import java.util.List;
import javax.persistence.EntityManager;
import jpa.entitys.synchro.common.ACTION_HANDLER;
import jpa.entitys.synchro.staging.MmPurchaseOrder;
import jpa.service.common.SessionEntityManager;
import jpa.service.synchro.staging.MmPurchaseOrderServices;
import org.apache.log4j.Logger;
import promis.utility.CommonService;
import sap.business.commons.services.CommonJCOReturn;
import apps.promis.in.construction.PurchaseOrderAction;
import com.sap.mw.jco.JCO;

/**
 * 
 * @author Chatree Siangklom of Administrator
 * Date =Dec 16, 2013 : 11:25:18 AM 
 * CreateBy=Chatree Siangklom
 * 
 * MmPurchaseOrderService
 * TODO
 */
public class MmPurchaseOrderService {
	private static final Logger log = Logger.getLogger(MmPurchaseOrderService.class);
	
	public void CreatedSync(JCO.ParameterList input, JCO.ParameterList tables, JCO.ParameterList output, String structureOrTableName) {
		List<MmPurchaseOrder> lst_object = new ArrayList<MmPurchaseOrder>();
		JCO.Table table = tables.getTable(structureOrTableName);
		int records = -1;
		List<MmPurchaseOrder> lst = null;
		try{
			
			records = table.getNumRows();

			EntityManager em = new SessionEntityManager().CreatedEntityManager();
			MmPurchaseOrderServices mmPurchaseOrderServ = new MmPurchaseOrderServices(em);
			
			String instance_no = mmPurchaseOrderServ.GetNewInstanceNo();
			
			for(int i = 0; i < records; i++)
			{
				table.setRow(i);
				MmPurchaseOrder model = new MmPurchaseOrder();
				
				//model.setPromisStagingId(CommonService.IsNullRNull(table.getString("PROMIS_TXN_ID")));
				model.setInstanceNo(instance_no);
				
				model.setSapCompanyCode(CommonService.IsNullRNull(table.getString("COMPANY_CODE")));
				model.setPoType(CommonService.IsNullRNull(table.getString("PO_TYPE")));
				
				model.setSapPlantCode(CommonService.IsNullRNull(table.getString("PROJECT")));
				
				//model.setPoSeries(CommonService.IsNullRNull(table.getString("PO_SERIES")));
				//log.info("PO_NO : " + table.getString("PO_NO"));
				//model.setPoNo(CommonService.IsNullRNull(table.getString("PO_NO")));
				
				model.setPoDate(CommonService.IsNullRNull(table.getString("PO_DATE")));
				model.setDepartmentCode(CommonService.IsNullRNull(table.getString("DEPARTMENT_CODE")));
				model.setCurrency(CommonService.IsNullRNull(table.getString("CURRENCY")));
				model.setExchangeRate(CommonService.IsNullRNull(table.getString("EXCHANGE_RATE")));
				model.setPoDiscountPercent(CommonService.IsNullRNull(table.getString("PO_DISCOUNT_PERCENT")));

				model.setSupplierCode(CommonService.IsNullRNull(table.getString("SUPPLIER_CODE")));
				model.setItemValueFc(CommonService.IsNullRNull(table.getString("ITEM_VALUE_FC")));
				model.setDiscountAmount(CommonService.IsNullRNull(table.getString("DISCOUNT_AMOUNT")));				
				
				model.setPoStatus(CommonService.IsNullRNull(table.getString("RELEASE_IND")));
				
				model.setPoDeliveryDate(CommonService.IsNullRNull(table.getString("PO_DELIVERYDATE")));
				
				if(!CommonService.IsNull(table.getString("SEQ_NO")))
					model.setSeqNo(CommonService.ConvertStringToBigDecimal(table.getString("SEQ_NO")));
				
				model.setItemCode(CommonService.IsNullRNull(table.getString("ITEM_CODE")));
				model.setItemDesc(CommonService.IsNullRNull(table.getString("ITEM_DESC")));
				model.setItemUmQty(CommonService.IsNullRNull(table.getString("ITEM_UM_QTY")));
				model.setItemUm(CommonService.IsNullRNull(table.getString("ITEM_UM")));
				model.setItemRate(CommonService.IsNullRNull(table.getString("ITEM_RATE")));
				model.setDiscountPercent(CommonService.IsNullRNull(table.getString("DISCOUNT_PERCENT")));
				model.setUnitNumber(CommonService.IsNullRNull(table.getString("UNIT_NUMBER")));
				model.setPrNo(CommonService.IsNullRNull(table.getString("PR_NO")));
				
				if(!CommonService.IsNull(table.getString("REF_PR_LINE_SEQ")))
					model.setRefPrLineSeq(CommonService.ConvertStringToBigDecimal(table.getString("REF_PR_LINE_SEQ")).toString());
				
				model.setVatIncludeFlag(CommonService.IsNullRNull(table.getString("VAT_INCLUDE_FLAG")));
				model.setTaxType(CommonService.IsNullRNull(table.getString("TAX_TYPE")));
				model.setPoLineStatus(CommonService.IsNullRNull(table.getString("PO_LINE_STATUS")));
				//model.setAdjustFlag(CommonService.IsNullRNull(table.getString("ADJUST_FLAG")));
				//model.setAdjustPoQty(CommonService.IsNullRNull(table.getString("ADJUST_PO_QTY")));
				
				model.setVatPercent(CommonService.IsNullRNull(table.getString("VAT_PERCENT")));
				model.setVatBaseAmountLc(CommonService.IsNullRNull(table.getString("VAT_BASE_AMOUNT_LC")));
				model.setDiscountAmountFc(CommonService.IsNullRNull(table.getString("DISCOUNT_AMOUNT_FC")));
				model.setVatAmountLc(CommonService.IsNullRNull(table.getString("VAT_AMOUNT_LC")));
				model.setNetAmountLc(CommonService.IsNullRNull(table.getString("NET_AMOUNT_LC")));
				
				model.setPoItemPrice(CommonService.IsNullRNull(table.getString("PO_ITEM_PRICE")));
				model.setPoDiscountAmount(CommonService.IsNullRNull(table.getString("PO_DISCOUNT_AMOUNT")));
				model.setPoNetItemPriceLc(CommonService.IsNullRNull(table.getString("PO_NET_ITEM_PRICE_LC")));
				model.setPoVatAmountLc(CommonService.IsNullRNull(table.getString("PO_VAT_AMOUNT_LC")));
				
				//Set Txn Reacord				
				model.setCreatedOn(CommonService.IsNullRNull(table.getString("CREATED_ON")));
				model.setCreatedBy(CommonService.IsNullRNull(table.getString("CREATED_BY")));
				model.setUpdatedOn(CommonService.IsNullRNull(table.getString("LAST_UPD_ON")));
				model.setUpdatedBy(CommonService.IsNullRNull(table.getString("LAST_UPD_BY")));
				
				if(CommonService.IsNull(table.getString("LAST_UPD_ON")))
					model.setActionHandle(ACTION_HANDLER.INSERTED.toString());
				else 
					model.setActionHandle(ACTION_HANDLER.UPDATED.toString());
				
				//Set SAP External Key link
				model.setExtRefKey(CommonService.IsNullRNull(table.getString("SYNC_EXTERNAL_REF_KEY")));
				model.setExtRefNo(CommonService.IsNullRNull(table.getString("SYNC_EXTERNAL_REF_NO")));
				model.setInterfaceNo("MM-T2-010");
				
				lst_object.add(model);
			}
			
			System.out.println("Insert to Staging size="+ CommonService.getSize(lst_object) +" --->");
			log.info("Insert to Staging size="+ CommonService.getSize(lst_object) +" --->");
			//Create To Staging
			mmPurchaseOrderServ.Inserted(lst_object);			
			
			//find by Instance 
			lst = mmPurchaseOrderServ.findByInstanceNo(instance_no);
			log.info("find by instance_no="+ instance_no +" mmPurchaseOrderSize = "+ CommonService.getSize(lst) +"--->");
			
			if(CommonService.getSize(lst) > 0){
				//Create to Promis
				try{
					
					new PurchaseOrderAction().CreateToPromis(lst.get(0).getExtRefNo(), lst.get(0).getInstanceNo());
					
					lst = mmPurchaseOrderServ.findByInstanceNo(instance_no);
					if(CommonService.getSize(lst) == records){
						for(int i = 0; i < records; i++)
						{
							MmPurchaseOrder obj = lst.get(i);
							table.setRow(i);
							table.setValue(CommonService.IsNullRString(obj.getPromisStagingId()), "PROMIS_TXN_ID");
							table.setValue(obj.getMsgCode(), "MSG_CODE");
							table.setValue(obj.getMsgDesc(), "MSG_DESC");
							table.setValue("", "MSG_ALT_DESC");
							table.setValue(obj.getExtRefNo(), "MSG_ACTION_RESULT");
							
							System.out.println("return Message PromisStagingId=" + CommonService.IsNullRString(obj.getPromisStagingId()) + " || MSG_DESC=" + obj.getMsgDesc());
							log.error("return Message PromisStagingId=" + CommonService.IsNullRString(obj.getPromisStagingId()) + " || MSG_DESC=" + obj.getMsgDesc());
							log.info(CommonJCOReturn.toString(table));
						}
					}else
						throw new Exception("Error mmPurchaseOrder in staging is not eq sap table !!!");
					
				}catch(Exception e){
					log.error(e.getMessage());
					System.out.println(e.getMessage());
					
					//When Error
					lst = mmPurchaseOrderServ.findByInstanceNo(instance_no);
					if(CommonService.getSize(lst) == records){
						for(int i = 0; i < records; i++)
						{
							MmPurchaseOrder obj = lst.get(i);
							table.setRow(i);
							table.setValue(CommonService.IsNullRString(obj.getPromisStagingId()), "PROMIS_TXN_ID");
							table.setValue(obj.getMsgCode(), "MSG_CODE");
							table.setValue(obj.getMsgDesc(), "MSG_DESC");
							table.setValue("", "MSG_ALT_DESC");
							table.setValue(obj.getExtRefNo(), "MSG_ACTION_RESULT");
							
							System.out.println("return Message PromisStagingId=" + CommonService.IsNullRString(obj.getPromisStagingId()) + " || MSG_DESC=" + obj.getMsgDesc());
							log.error("return Message PromisStagingId=" + CommonService.IsNullRString(obj.getPromisStagingId()) + " || MSG_DESC=" + obj.getMsgDesc());
							log.info(CommonJCOReturn.toString(table));
						}
					}else
						throw new Exception("Error mmPurchaseOrder in staging is not eq sap table !!!");
					
				}
			}else{
				System.out.println("find not found  instance no=" + instance_no);
				log.info("find not found  instance no=" + instance_no);	
			}
		}
		catch(Exception e)
		{
			System.out.println(e.getMessage());
			log.error(e.getMessage());
			
			//Create to Promis
			if(CommonService.getSize(lst) == records){
				for(int i = 0; i < records; i++)
				{
					MmPurchaseOrder obj = lst.get(i);
					table.setRow(i);
					table.setValue(CommonService.IsNullRString(obj.getPromisStagingId()), "PROMIS_TXN_ID");
					table.setValue("E", "MSG_CODE");
					table.setValue(e.getMessage(), "MSG_DESC");
					table.setValue(e.getMessage(), "MSG_ALT_DESC");
					table.setValue(obj.getExtRefNo(), "MSG_ACTION_RESULT");
					
					try {
						
						System.out.println("PromisStagingId=" + CommonService.IsNullRString(obj.getPromisStagingId()) + " || Message=" + e.getMessage());
						log.info("PromisStagingId=" + CommonService.IsNullRString(obj.getPromisStagingId()) + " || Message=" + e.getMessage());
						log.info(CommonJCOReturn.toString(table));
						
					} catch (Exception e1) {
						System.out.println(e1.getMessage());
						log.info(e1.getMessage());
					}
				}
			}else
			{			
				for(int i = 0; i < records; i++)
				{
					table.setRow(i);
					table.setValue("E", "MSG_CODE");
					table.setValue("Error mmPurchaseOrder in staging sap table records="+ records + " || " + e.getMessage(), "MSG_DESC");
					System.out.println("Error mmPurchaseOrder in staging sap table records="+ records + " || " + e.getMessage());
					log.info("Error mmPurchaseOrder in staging sap table records="+ records + " || " + e.getMessage());
				}
			}
		}
	}
}
